package com.ai.enviro.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 数据源配置
 *
 * @author 71555554
 * @date 2020-11-09
 * <p>
 * 双数据源配置信息
 */
@Configuration
@MapperScan(basePackages = SystemDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "systemSqlSessionFactory")
public class SystemDataSourceConfig {

    static final String PACKAGE = "com.ai.enviro.mapper.system";

    static final String MAPPER_LOCATION = "classpath*:mapper/system/*.xml";

    @Value("${system.datasource.url}")
    private String jdbcUrl;

    @Value("${system.datasource.driverClassName}")
    private String jdbcDriverClassName;

    @Value("${system.datasource.username}")
    private String jdbcUsername;

    @Value("${system.datasource.password}")
    private String jdbcPassword;

    /**
     * 数据源
     *
     * @return DataSource
     */
    @Bean(name = "systemDataSource")
    @Primary
    public DataSource systemDataSource() {
        DruidDataSource datasource = new DruidDataSource();
        // 数据库驱动
        datasource.setDriverClassName(jdbcDriverClassName);
        // 相应驱动的jdbcUrl
        datasource.setUrl(jdbcUrl);
        // 数据库的用户名
        datasource.setUsername(jdbcUsername);
        // 数据库的密码
        datasource.setPassword(jdbcPassword);
        // 每个分区最大的连接数
        datasource.setMaxActive(20);
        // 每个分区最小的连接数
        datasource.setMinIdle(5);
        //获取连接时最大等待时间，单位毫秒
        datasource.setMaxWait(10_000);
        datasource.setLoginTimeout(5);
        datasource.setTimeBetweenEvictionRunsMillis(600_000);
        datasource.setValidationQuery("SELECT 1 FROM DUAL");
        datasource.setTestWhileIdle(true);
        datasource.setQueryTimeout(300);
        datasource.setConnectTimeout(10_000);
        datasource.setSocketTimeout(300_000);

        return datasource;
    }

    /**
     * 事物配置
     *
     * @return Transaction
     */
    @Bean(name = "systemTransactionManager")
    @Primary
    public DataSourceTransactionManager systemTransactionManager() {
        return new DataSourceTransactionManager(systemDataSource());
    }

    /**
     * 模版
     *
     * @param sqlSessionFactory factory
     * @return template
     * @throws Exception e
     */
    @Bean(name = "systemSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate secondarySqlSessionTemplate(
            @Qualifier("systemSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * SqlSessionFactory
     *
     * @param systemDataSource DataSource
     * @return SqlSessionFactory
     */
    @Bean(name = "systemSqlSessionFactory")
    @Primary
    public SqlSessionFactory systemSqlSessionFactory(@Qualifier("systemDataSource") DataSource systemDataSource) {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        try {
            sqlSessionFactoryBean.setDataSource(systemDataSource);
            // 设置别名包（实体类）
            sqlSessionFactoryBean.setTypeAliasesPackage("com.yum.trading.center.order.model.system");
            // 设置mybatis的主配置文件
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            // 设置sql配置文件路径
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources(MAPPER_LOCATION));
            // 分页
            Interceptor interceptor = new PageInterceptor();
            Properties properties = new Properties();
            properties.setProperty("helperDialect", "mysql");
            properties.setProperty("offsetAsPageNum", "true");
            properties.setProperty("rowBoundsWithCount", "true");
            properties.setProperty("reasonable", "false");
            interceptor.setProperties(properties);
            return sqlSessionFactoryBean.getObject();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
